import { Button, DatePicker, Form, Input, Select, notification, Icon } from 'antd';
import React, { Fragment, ReactNode } from 'react';
import _ from 'lodash';
import { connect } from 'dva';
// eslint-disable-next-line import/no-extraneous-dependencies
import { withRouter } from 'react-router-dom';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import moment, { Moment } from 'moment';

import DetailDialog from '@/pages/finance/recharge/components/detailDialog/index';
import CreateDetailDialog from './components/createDialog';
import RepairDetailDialog from './components/detailDialog';
import Mtable from '../components/Mtable/index';

import { getLogsColumns, addSign } from './utils';
import { setCommonFun } from '@/utils/tools';
import {
  getTableFiltersData,
  initialTimeWithMill,
  getErrTip,
  checkShowOpt,
  urlEncode,
} from '../utils';
import { getMerchant } from '../service';
import { SUCCESS_CODE } from '../data';
import { checkPermission } from '@/utils/resolvePermission';

interface StateType {
  [propName: string]: any;
}

interface PropType {
  [propName: string]: any;
}

function openNotification(msg: string, description: string) {
  notification.open({
    message: msg,
    description,
    duration: null,
    icon: <Icon type="check-circle" style={{ color: '#108ee9' }} />,
  });
}

// 初始化表单筛选项
function initTableFilters(): object {
  return {
    orderStatus: '0,1,2,3,4,5,6,7', // 订单状态
    remark: undefined,
    limitType: '-1', // 充值类型  -1：全部 1：普通充值 2：大额充值
    userType: '-1',
    // channelId: undefined,
  };
}

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;
const orderPath = '/api/gl/recharge/manage/create/order';
const stormOrderPath = '/api/gl/recharge/manage/create/order/forStormPay';

@setCommonFun
class Logs extends React.PureComponent<PropType, StateType> {
  public state: StateType = {
    tableFilters: initTableFilters(),
    detailDialogVisible: false,
    rowData: {},
    merchantList: [],
    errTip: false,
    createDialogVisible: false,
    repairDialogVisible: false,
    isShowOpt: false,
  };

  public refMtable: any = React.createRef();

  componentDidMount() {
    this.getMerchantList();
  }

  // 检测时间和订单号，必须填一个
  private checkTimeAndOrderId = (time: Moment[], orderId: string) => {
    const { errTip } = this.state;
    let flag: boolean;
    if (time.length < 1 && !orderId && !errTip) {
      flag = true;
    }
    if ((time.length > 0 || orderId) && errTip) {
      flag = false;
    }
    this.setState({ errTip: flag });
    return !flag;
  };

  // 打开创建订单弹窗
  private handleCreate = () => {
    this.setState({
      createDialogVisible: true,
    });
  };

  // 创建订单 - 保存
  private createOrderEffect = (payload: object, isStorm: boolean) => {
    if (isStorm) {
      this.props.dispatch({
        type: 'recharge/repairCreateStormEffect',
        payload,
        callback: (response: { code: number; message: string; data: any }) => {
          const { code, data } = response;
          if (code === SUCCESS_CODE) {
            openNotification('创建订单成功', `订单号：${data.tradeNo}`);
            this.setState({ createDialogVisible: false });
            this.refMtable.current.getTableData();
          }
        },
      });
      return;
    }

    const urlStr = urlEncode({
      ...payload,
      ...addSign(),
    }).substr(1);
    const path = isStorm ? stormOrderPath : orderPath;
    window.open(`${path}?${urlStr}`, '_blank');
    this.setState({ createDialogVisible: false });
    this.refMtable.current.getTableData();
  };

  // 关闭详情弹窗
  private handleDetailDialogClose = () => {
    this.setState({
      repairDialogVisible: false,
      rowData: {},
    });
  };

  // 补单操作
  private handleDetail = (rowData: any) => {
    const isShowOpt = checkShowOpt(rowData);
    const { channelId } = rowData;
    if (channelId === 1001 || channelId === 1003) {
      this.getBankListEffect({ channelId: rowData.channelId, rechargeType: 0 });
    }
    this.setState({
      repairDialogVisible: true,
      rowData,
      isShowOpt,
    });
  };

  // 获取银行列表
  private getBankListEffect = (payload: object) => {
    this.props.dispatch({
      type: 'recharge/setWithdrawBankEffect',
      payload,
    });
  };

  // 渲染表单
  private renderFilters = (): ReactNode => {
    const { getFieldDecorator } = this.props.form;
    const { errTip, merchantList } = this.state;
    const tip = getErrTip(errTip);

    return (
      <Form layout="inline" onSubmit={this.handleSubmit}>
        <FormItem>
          {getFieldDecorator('dateType', {
            initialValue: 1,
          })(
            <Select style={{ width: 120 }}>
              {/* 充值时间 */}
              <Option value={1}>
                {formatMessage({ id: 'recharge-logs.filters.recharge-time' })}
              </Option>
              {/* 到账时间 */}
              <Option value={2}>
                {formatMessage({ id: 'recharge-logs.filters.arrival-time' })}
              </Option>
            </Select>,
          )}
        </FormItem>

        <FormItem {...tip.timeTip}>
          {getFieldDecorator('time', {
            initialValue: initialTimeWithMill(7),
          })(
            <RangePicker
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={[
                formatMessage({ id: 'recharge-logs.filters.start-time' }),
                formatMessage({ id: 'recharge-logs.filters.end-time' }),
              ]}
              showTime={{
                hideDisabledOptions: true,
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }}
              onChange={(dates: Moment[]) => {
                const orderId = this.props.form.getFieldValue('orderId').trim();
                this.checkTimeAndOrderId(dates, orderId);
              }}
            />,
          )}
        </FormItem>

        {/* 充值单号 */}
        <FormItem
          label={<FormattedMessage id="recharge-logs.filters.order-id" />}
          {...tip.orderIdTip}
        >
          {getFieldDecorator('orderId', {
            initialValue: '',
          })(
            <Input
              placeholder={formatMessage({ id: 'recharge-logs.filters.order-id-placeholder' })}
              onChange={(e: any) => {
                const { value } = e.target;
                const orderId = value.trim();
                const time = this.props.form.getFieldValue('time');
                this.checkTimeAndOrderId(time, orderId);
              }}
            />,
          )}
        </FormItem>

        {/* 账户名 */}
        <FormItem label={<FormattedMessage id="recharge-logs.filters.account-name" />}>
          {getFieldDecorator('userName', {
            initialValue: '',
          })(
            <Input
              placeholder={formatMessage({ id: 'recharge-logs.filters.account-name-placeholder' })}
            />,
          )}
        </FormItem>

        {/* 手机号 */}
        <FormItem label={<FormattedMessage id="recharge-logs.filters.form-tel" />}>
          {getFieldDecorator('telephone')(
            <Input
              placeholder={formatMessage({ id: 'recharge-logs.filters.form-tel-placeholder' })}
              allowClear
            />,
          )}
        </FormItem>

        {/* 姓名 */}
        <FormItem label={<FormattedMessage id="recharge-logs.filters.form-really-name" />}>
          {getFieldDecorator('reallyName', {
            initialValue: '',
          })(
            <Input
              placeholder={formatMessage({
                id: 'recharge-logs.filters.form-really-name-placeholder',
              })}
              allowClear
            />,
          )}
        </FormItem>

        {/* 充值商户 */}
        <FormItem label={<FormattedMessage id="recharge-logs.filters.form-recharge-merchant" />}>
          {getFieldDecorator('channelId')(
            <Select
              style={{ width: 120 }}
              showSearch
              filterOption={(input, option: any) => option.props.children.indexOf(input) >= 0}
            >
              {merchantList.map((item: any) => (
                <Option key={item.channelId} value={item.channelId}>
                  {item.channelName}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>

        <FormItem>
          {/* 查询 */}
          <Button type="primary" htmlType="submit" disabled={errTip}>
            {formatMessage({ id: 'recharge-logs.filters.search-btn' })}
          </Button>
          {/* 重置 */}
          <Button style={{ marginLeft: '10px' }} onClick={this.handleReset}>
            {formatMessage({ id: 'recharge-logs.filters.reset-btn' })}
          </Button>
          {/* 创建订单 */}
          {checkPermission(this.props.btns, 'new-finance-report-logs-create') ? (
            <Button style={{ marginLeft: '10px' }} onClick={this.handleCreate}>
              创建订单
            </Button>
          ) : null}
        </FormItem>
      </Form>
    );
  };

  // 渲染表格
  private renderTable = (): ReactNode => {
    const { logsData } = this.props.recharge;
    const style = { wordBreak: 'break-all' };
    const { tableFilters } = this.state;

    return (
      <Mtable
        amountSum={logsData.amountSum}
        countSum={logsData.countSum}
        tableFilters={tableFilters}
        style={style}
        dataSource={logsData}
        columns={getLogsColumns(this, this.state.merchantList)}
        dispatch={this.props.dispatch}
        effectType="recharge/getLogsListEffect"
        validateFields={this.props.form.validateFieldsAndScroll}
        setEffectParams={this.setEffectParams}
        scroll={{ x: 2580, y: 540 }}
        ref={this.refMtable}
      />
    );
  };

  // 搜索
  private handleSubmit = (e: React.SyntheticEvent) => {
    e.preventDefault();
    const time = this.props.form.getFieldValue('time');
    const orderId = this.props.form.getFieldValue('orderId').trim();
    if (!this.checkTimeAndOrderId(time, orderId)) {
      this.setState({ errTip: true });
    } else {
      this.refMtable.current.initPage(() => this.refMtable.current.getTableData());
    }
  };

  // 获取已经配置商户的充值渠道账号
  private getMerchantList = () => {
    getMerchant().then((res: any) => {
      if (res) {
        const { code, data } = res;
        if (code === SUCCESS_CODE && data) {
          this.setState({ merchantList: data });
        }
      }
    });
  };

  // 重置
  private handleReset = () => {
    this.props.form.resetFields();
    this.setState(
      {
        tableFilters: initTableFilters(),
        errTip: false,
      },
      () => {
        this.refMtable.current.getTableData();
      },
    );
  };

  // 处理表头筛选项
  private setEffectParams = (filters?: any) => {
    const tableFiltersData: any = filters ? getTableFiltersData(filters) : {};
    if (filters) {
      const { orderStatus } = tableFiltersData;
      if (!orderStatus.length) {
        const initTableFiltersData: any = initTableFilters();
        tableFiltersData.orderStatus = initTableFiltersData.orderStatus;
      }
      this.setState({ tableFilters: tableFiltersData });
    }
    return { ...tableFiltersData, paymentId: '-1' };
  };

  render(): ReactNode {
    const {
      detailDialogVisible,
      rowData,
      createDialogVisible,
      repairDialogVisible,
      isShowOpt,
    } = this.state;

    return (
      <Fragment>
        {this.renderFilters()}
        {this.renderTable()}

        {detailDialogVisible ? (
          <DetailDialog
            visible={detailDialogVisible}
            rowData={rowData}
            close={() => {
              this.setState({
                detailDialogVisible: false,
                rowData: {},
              });
            }}
          />
        ) : null}
        {createDialogVisible ? (
          <CreateDetailDialog<>
            visible={createDialogVisible}
            cancle={() => {
              this.setState({ createDialogVisible: false });
            }}
            confirm={this.createOrderEffect}
          />
        ) : null}
        {repairDialogVisible ? (
          <RepairDetailDialog<>
            visible={repairDialogVisible}
            data={rowData}
            showOpt={isShowOpt}
            confirm={() => {
              this.handleDetailDialogClose();
              this.refMtable.current.getTableData();
            }}
            close={this.handleDetailDialogClose}
          />
        ) : null}
      </Fragment>
    );
  }
}

const LogsContainer = Form.create({ name: 'rechargeLogs' })(Logs);

export default withRouter(
  connect(({ recharge, global }: { recharge: any; global: any }) => ({
    recharge,
    btns: global.btns,
  }))(LogsContainer),
);
